package com.yearno.baseframe.http

import com.google.gson.JsonParser
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.ResponseBody.Companion.toResponseBody
import okhttp3.logging.HttpLoggingInterceptor

object HttpClientManager {


    private val mApiHttpClient: OkHttpClient = OkHttpClient.Builder()
        .addInterceptor(getInterceptor())
        .addInterceptor(commonInterceptor())
        .addNetworkInterceptor(responseInterceptor())
        .sslSocketFactory(
            SSLHelper.sslSocketFactory,
            SSLHelper.getX509TrustManager()
        )
        .hostnameVerifier(SSLHelper.hostnameVerifier)
        .build()

    fun getApiHttpClient(): OkHttpClient {
        return mApiHttpClient
    }

    fun getWebSocketHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(getInterceptor())
            .sslSocketFactory(
                SSLHelper.sslSocketFactory,
                SSLHelper.getX509TrustManager()
            )
            .hostnameVerifier(SSLHelper.hostnameVerifier)
            .build()
    }

    private fun getInterceptor(): Interceptor {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        return interceptor
    }

    private fun commonInterceptor(): Interceptor {
        return Interceptor { chain ->
            val request = chain.request()
            val newBuilder = request.newBuilder().apply {
                //添加这个header,避免了responseInterceptor中由于OkHttp内部Gzip处理而引起乱码的问题
                addHeader("Accept-Encoding", "identity")
            }
            chain.proceed(newBuilder.build())
        }
    }

    /**
     * 响应数据预处理：
     * 1.由于系统维护时，result的字段返回的数据类型会变更为数据维护信息的数据，故在此拦截并处理系统维护数据
     */
    private fun responseInterceptor(): Interceptor {
        return Interceptor { chain ->
            val response = chain.proceed(chain.request())
            val body = response.body
            val content = body?.bytes()
            val contentType = body?.contentType()
            val subtype = contentType?.subtype//数据类型
            try {
                //请求成功，并且subType是Json类型时才处理
                if (response.isSuccessful && subtype?.contains("json") == true) {
                    content?.let {
                        val jsonStr = String(it)
                        val jsonObject = JsonParser.parseString(jsonStr).asJsonObject
                        val code = jsonObject.get("code").asString
                        //系统维护,Session中设置系统维护信息

                    }
                }
            } catch (e: Exception) {
            }
            response.newBuilder().body(content?.toResponseBody(contentType)).build()
        }
    }
}
